package chapter8;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/*
@WebFilter(
		filterName = "authorityFilter",
		urlPatterns = {"/*"},
		initParams = {
		     @WebInitParam(name = "encoding", value = "UTF-8"),		
		     @WebInitParam(name = "loginPage", value = "chapter8/login.jsp"),		
		     @WebInitParam(name = "proLogin", value = "proLogin.jsp")				
		})*/
public class AuthorityFilter implements Filter{
	private FilterConfig config;
	
	@Override
	public void init(FilterConfig fconfig) throws ServletException {
		config = fconfig;
	}
	


	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//获取该过滤器的配置参数
		String encoding = config.getInitParameter("encoding");
		String loginPage = config.getInitParameter("loginPage");
		String proLogin = config.getInitParameter("proLogin");
		
		//设置字符编码集
		request.setCharacterEncoding(encoding);
		response.setContentType("text/html;charset=utf-8");
		
		HttpServletRequest hrequest = (HttpServletRequest)request;
		HttpSession session = hrequest.getSession(true);

		//获取客户请求的页面
		String requestPath = hrequest.getServletPath();
		//如果session作用域的user为null，表明没有登录
		//即用户请求的即不是登录页面，也不是处理登录的页面
		if(session.getAttribute("user") == null
				&& !requestPath.endsWith(loginPage)
				&& !requestPath.endsWith(proLogin)){
			//转发到登录页面
			request.setAttribute("message", "您还没有登录！");
			request.getRequestDispatcher("/"+loginPage).forward(request, response);
		}else{
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void destroy() {
		config = null;
	}

}
